package com.ylx.web.l;


import com.ylx.service.AdminTsuService;
import org.apache.commons.fileupload.FileItem;
import org.apache.commons.fileupload.FileUploadException;
import org.apache.commons.fileupload.disk.DiskFileItemFactory;
import org.apache.commons.fileupload.servlet.ServletFileUpload;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.*;
import java.util.Arrays;
import java.util.Iterator;
import java.util.List;



/**
 * Servlet implementation class Uploadfile
 */
@WebServlet("/uploadfile")
  public  class Uploadfile extends HttpServlet {
    private static final long serialVersionUID = 1L;

    /**
     * @see HttpServlet#HttpServlet()
     */
    public Uploadfile() {
        super();
        // TODO Auto-generated constructor stub
    }

    /**
     * @see HttpServlet#doGet(HttpServletRequest request, HttpServletResponse response)
     */
    protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        // TODO Auto-generated method stub
        //response.getWriter().append("Served at: ").append(request.getContextPath());


    }

    /**
     * @see HttpServlet#doPost(HttpServletRequest request, HttpServletResponse response)
     */
    protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        // TODO Auto-generated method stub
        doGet(request, response);
        //设置编码方式
        request.setCharacterEncoding("utf-8");
        response.setCharacterEncoding("gb2312");


        //设置输出
        PrintWriter outprint = response.getWriter();
        //Enumeration files = multipartRequest.getFileNames();
        //设置文件目录
        String webroot = this.getServletContext().getRealPath("/");
        File temppath = new File(webroot + "fileuploadtemp");
        String dir = webroot+ File.separator + "upload";
        File path = new File(webroot+ File.separator + "upload");
        if (!temppath.exists()) {
            temppath.mkdirs();
        }
        if (!path.exists()) {
            path.mkdirs();
        }

        //设置文件类型(可加)
        String[] type= new String[]{".jpg",".png",".jpeg",".gif",".bmp"};

        //创建文件项工厂
        DiskFileItemFactory factory = new DiskFileItemFactory(1024 * 1024,temppath);
        ServletFileUpload upload = new ServletFileUpload(factory);
        upload.setFileSizeMax(1024 * 1024 * 10);
        try {
            List<FileItem> fileItems = upload.parseRequest(request);
            Iterator<FileItem> it = fileItems.iterator();
            String newFimeName=null;
            String tstitle1=null;
            String tscontent1=null;
            //String tstitle2=null;
            //String tscontent2=null;
            //String name1 = "tstitle";
            //String content1 = "tscontent";
            // int count = 0;

            //遍历request file
            while (it.hasNext()) {
                FileItem fi = it.next();

                //判断该表单是否为普通表单类型
                if (fi.isFormField()) {
                    String nameString = fi.getFieldName();
                    switch(nameString)
                    {
                        case "tstitle" :
                            //解决转换字节流乱码问题
                            tstitle1 =  new String(fi.getString().getBytes("ISO8859_1"),"utf-8");

                            System.out.println(tstitle1);
                            break;
                        case "tscontent" :
                            tscontent1 =  new String(fi.getString().getBytes("ISO8859_1"),"utf-8");
                            System.out.println(tscontent1);
                            break;
                        default :
                            System.out.println("未知等级");

                    }

                    //System.out.println("----"+nameString+"-------");
                    //System.out.println("----"+conString+"-------");
                } else {
                    InputStream in = fi.getInputStream();
                    String name = fi.getName();//获得文件原名

                    //得到文件后缀名
                    int index = name.lastIndexOf(".");
                    String endWith = name.substring(index);

                    //判断是否符合类型
                    boolean TypeExists = Arrays.asList(type).contains(endWith);
                    if (!TypeExists) {
                        outprint.print("<script>\n" +
                                "alert(\"文件类型错误，只允许jpg,png,jpeg,gif\");location=\"fileup.html\";\n" +
                                "</script>");
                        return;
                    }

                    newFimeName = System.currentTimeMillis() + endWith;//新文件名

                    //创建上传文件
                    FileOutputStream out = new FileOutputStream(new File(
                            dir + "/" + newFimeName));

                    byte buffer[] = new byte[1024];
                    int len = 0;
                    while ((len = in.read(buffer)) > 0) {
                        out.write(buffer, 0, len);//写入大小
                    }

                    in.close();
                    out.close();
                    fi.delete();

                    //  outprint.print("上传成功");
                }
            }

            AdminTsuService tsuService = new AdminTsuService();
           tsuService.addone(tstitle1, tscontent1,newFimeName);//调用service层方法

            outprint.flush();//清除缓冲区的数据
            outprint.close();//关闭流
        } catch(FileUploadException e){
            response.getWriter().write(e.toString());
        }
    }
}